package com.tanhua.sso.service;

import com.tanhua.sso.utils.HttpUtils;
import com.tanhua.sso.config.AliyunSMSConfig;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public String sendSms(String phoneNumber) {

        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = this.aliyunSMSConfig.getAppcode();// "477109dcf2ad44b298f717f596e39973"; // "你自己的AppCode";

        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        Map<String, String> querys = new HashMap<String, String>();

        int outTime = 5; // 超时时间
        int verification = RandomUtils.nextInt(100000, 999999); // 验证码
        String content = "code:" + verification + ",expire_at:" + outTime;

        Map<String, String> bodys = new HashMap<String, String>();
//        bodys.put("content", "code:天气太热了——阿帆的小测试,expire_at:5");
//        bodys.put("content", "code:云坨坨猛虎下山，考出了好成绩，进了大学不要贪吃。——来自阿帆老哥的祝福~,expire_at:666");
        bodys.put("content", content);
        bodys.put("phone_number", phoneNumber); // 15773706036
        bodys.put("template_id", "TPL_0001");

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            // 获取response的body
//            System.out.println(EntityUtils.toString(response.getEntity()));

            return verification + "";
        } catch (Exception e) {
            log.error("短信验证码发送失败 ~ phoneNumber = " + phoneNumber, e);
        }

        return null;
    }

    /**
     * 短信发送业务
     *
     * @param phone
     * @return
     */
    public ErrorResult sendCheckCode(String phone) {
        // 先判断该手机号验证码是否已发出，并且在有效时间内
        String redisKey = "CHECK_CODE_" + phone;

        // 判断验证码是否存在
        if (this.redisTemplate.hasKey(redisKey)) {
            String msg = "上一次发送的验证码还未失效！";
            return ErrorResult.builder().errCode("000001").errMessage(msg).build();
        }

        // 发送短信
        // String code = this.sendSms(phone);
        String code = "123456";
        // 判断短信是否发送成功
        if (code == null) {
            String msg = "发送验证码失败！";
            return ErrorResult.builder().errCode("000000").errMessage(msg).build();
        }

        // 将验证码存入到redis中，有效时间为5分钟
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofMinutes(5));

        System.out.println(this.redisTemplate.opsForValue().get(redisKey));

        return null;
    }
}
